# models.py
from gate_api import Configuration, ApiClient, FuturesApi
from gate_api.exceptions import ApiException, GateApiException
from app.common.utils import convert_order_to_serializable


def query_futures_accountq(gate_key, gate_secret, settle='usdt'):
    """ 查询合约账户信息 """
    configuration = Configuration(
        host="https://api.gateio.ws/api/v4",
        key=gate_key,
        secret=gate_secret
    )
    api_client = ApiClient(configuration)
    api_instance = FuturesApi(api_client)

    try:
        # 查询合约账户信息
        api_response = api_instance.list_futures_accounts(settle)
        return {"data": api_response.to_dict(), "message": "查询成功"}
    except GateApiException as ex:
        return {"message": f"Gate API异常, 标签: {ex.label}, 信息: {ex.message}", "code": 500}
    except ApiException as e:
        return {"message": f"API调用异常: {e}", "code": 500}


def query_futures_orders(gate_key, gate_secret, settle='usdt', status='open', contract=None, limit=100, offset=0,
                         last_id=None):
    """查询期货订单列表"""
    configuration = Configuration(
        host="https://api.gateio.ws/api/v4",
        key=gate_key,
        secret=gate_secret
    )
    api_client = ApiClient(configuration)
    api_instance = FuturesApi(api_client)

    try:
        # 根据订单状态动态添加查询参数
        if status == 'open':
            api_response = api_instance.list_futures_orders(settle, status, contract=contract)
        else:
            api_response = api_instance.list_futures_orders(settle, status, contract=contract, limit=limit,
                                                            offset=offset, last_id=last_id)

        # 处理 API 响应，将所有数据转换为可序列化的格式
        orders = [convert_order_to_serializable(order) for order in api_response]
        return {"code": 200, "data": orders, "total": len(orders), "msg": "订单列表查询成功"}
    except GateApiException as ex:
        return {"code": ex.status, "msg": f"Gate API异常, 标签: {ex.label}, 信息: {ex.message}"}
    except ApiException as e:
        return {"code": 500, "msg": f"API调用异常: {e}"}


# open - 开放的订单，这些订单当前处于未成交状态，等待市场成交。
# finished - 已完成的订单，这些订单已经被完全成交或已经被取消，不再活跃。
# cancelled - 已取消的订单，指明订单未完全成交就被取消了。

def query_user_positions(gate_key, gate_secret, settle='usdt', holding=True, limit=100, offset=0):
    """查询用户的持仓信息"""
    configuration = Configuration(
        host="https://api.gateio.ws/api/v4",
        key=gate_key,
        secret=gate_secret
    )
    api_client = ApiClient(configuration)
    api_instance = FuturesApi(api_client)

    try:
        # 获取用户持仓列表
        api_response = api_instance.list_positions(settle, holding=holding, limit=limit, offset=offset)
        positions = [position.to_dict() for position in api_response]
        return {"code": 200, "data": positions, "msg": "用户持仓查询成功"}
    except GateApiException as ex:
        return {"code": ex.status, "msg": f"Gate API异常, 标签: {ex.label}, 信息: {ex.message}"}
    except ApiException as e:
        return {"code": 500, "msg": f"API调用异常: {e}"}


def query_user_positions_task(gate_key, gate_secret, settle='usdt', holding=True, limit=100, offset=0):
    stop_event = threading.Event()

    def task():
        while not stop_event.is_set():
            try:
                response = query_user_positions(gate_key, gate_secret, settle, holding, limit, offset)
                socketio.emit('user_positions', {'data': response}, namespace='/')
                time.sleep(0.5)  # 每500毫秒请求一次
            except Exception as e:
                socketio.emit('error', {'message': f"Error querying user positions: {str(e)}"}, namespace='/')
                break  # 如果发生错误，中断循环

    thread = threading.Thread(target=task)
    thread.start()

    return stop_event

def query_single_futures_contract(gate_key, gate_secret, settle, contract):
    """查询单个合约的详细信息"""
    configuration = Configuration(
        host="https://api.gateio.ws/api/v4",
        key=gate_key,
        secret=gate_secret
    )
    api_client = ApiClient(configuration)
    api_instance = FuturesApi(api_client)

    try:
        api_response = api_instance.get_futures_contract(settle, contract)
        return {"code": 200, "data": api_response.to_dict(), "msg": "合约查询成功"}
    except GateApiException as ex:
        return {"code": ex.status, "msg": f"Gate API异常, 标签: {ex.label}, 信息: {ex.message}"}
    except ApiException as e:
        return {"code": 500, "msg": f"API调用异常: {e}"}


def query_futures_tickers(gate_key, gate_secret, settle='usdt', contract=None):
    """ 查询期货合约的行情信息 """
    configuration = Configuration(
        host="https://api.gateio.ws/api/v4",
        key=gate_key,
        secret=gate_secret
    )
    api_client = ApiClient(configuration)
    api_instance = FuturesApi(api_client)

    try:
        if contract:
            api_response = api_instance.list_futures_tickers(settle, contract=contract)
        else:
            api_response = api_instance.list_futures_tickers(settle)
        return {"code": 200, "data": [ticker.to_dict() for ticker in api_response], "msg": "行情信息查询成功"}
    except GateApiException as ex:
        return {"code": ex.status, "msg": f"Gate API异常, 标签: {ex.label}, 信息: {ex.message}"}
    except ApiException as e:
        return {"code": 500, "msg": f"API调用异常: {e}"}


def query_futures_account(gate_key, gate_secret, settle, contract):
    """查询合约账户信息"""
    configuration = Configuration(
        host="https://api.gateio.ws/api/v4",
        key=gate_key,
        secret=gate_secret
    )
    api_client = ApiClient(configuration)
    api_instance = FuturesApi(api_client)

    try:
        # 查询合约账户信息
        api_response = api_instance.list_futures_accounts(settle)
        return {"code": 200, "data": api_response.to_dict(), "msg": "合约账户查询成功"}
    except GateApiException as ex:
        return {"code": ex.status, "msg": f"Gate API异常, 标签: {ex.label}, 信息: {ex.message}"}
    except ApiException as e:
        return {"code": 500, "msg": f"API调用异常: {e}"}
